package cn.wolfcode.cloud.shop.mq;

import cn.wolfcode.cloud.shop.ws.WebSocketServer;
import cn.wolfcode.shop.common.Result;
import cn.wolfcode.shop.consts.MQConstents;
import cn.wolfcode.shop.mq.msg.SeckillSuccessMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;

@Component
@RocketMQMessageListener(
        topic = MQConstents.SECKILL_ORDER_TOPIC,
        selectorExpression = MQConstents.SECKILL_SUCCESS_TAG,
        consumerGroup = MQConstents.SECKILL_SUCCESS_CONSUMER_GROUP
)
@Slf4j
public class SeckillSuccessMQListener implements RocketMQListener<SeckillSuccessMsg> {

    @Override
    public void onMessage(SeckillSuccessMsg msg) {
        // 接收到秒杀成功后的消息，通知用户订单创建成功
        log.info("订单：{}创建成功", JSON.toJSONString(msg));

        try {
            Session session = WebSocketServer.clients.get(msg.getUuid());
            if (session != null) {
                String json = JSON.toJSONString(Result.success(msg));
                session.getBasicRemote().sendText(json);
            } else {
                log.warn("找不到客户端：{}的连接", msg.getUuid());
            }
        } catch (IOException e) {
            log.error("对不起！您的订单状态出现异常，请联系客服处理！", e);
        }
    }
}
